<script setup>
import {ref, onMounted} from 'vue'
import {Plus, Minus} from '@element-plus/icons-vue'
import axios from 'axios'
import {ElMessage} from 'element-plus'

const stockList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取库存列表
const getStockList = async () => {
  try {
    const response = await axios.get('/carRepair/admin/partManage/stock', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      stockList.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取库存列表失败:', error)
    ElMessage.error('获取库存列表失败')
  }
}

// 更新库存信息
const updateStock = async (stock) => {
  try {
    const {supplierName, partTypeName, partName, imageUrl, ...updateStock} = stock;
    const response = await axios.put('/carRepair/admin/partManage/stock', updateStock)
    if (response.data.code === 200) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新库存信息失败:', error)
    ElMessage.error('更新库存信息失败')
  }
}

// 处理最低库存预警值变化
const handleMinStockChange = async (stock, change) => {
  const newValue = stock.minStock + change
  if (newValue >= 0) {
    stock.minStock = newValue
    await updateStock(stock)
  }
}

// 处理零售单价变化
const handleRetailPriceChange = async (stock, change) => {
  const newValue = Number((stock.retailPrice + change).toFixed(2))
  if (newValue >= 0) {
    stock.retailPrice = newValue
    await updateStock(stock)
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getStockList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getStockList()
}

onMounted(() => {
  getStockList()
})
</script>

<template>
  <div class="stock-manage">
    <el-card>
      <el-table :data="stockList" style="width: 100%">
        <el-table-column label="零件图片" width="120">
          <template #default="scope">
            <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="150"></el-table-column>
        <el-table-column prop="partTypeName" label="零件类型名称" width="120"></el-table-column>
        <el-table-column prop="partName" label="零件名称" width="150"></el-table-column>
        <el-table-column prop="stockQuantity" label="当前库存" width="120">
          <template #default="scope">
            <span :class="{ 'stock-warning': scope.row.stockQuantity <= scope.row.minStock }">
              {{ scope.row.stockQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="最低库存预警值" width="200">
          <template #default="scope">
            <div class="number-input">
              <el-input-number
                  v-model="scope.row.minStock"
                  :min="0"
                  size="small"
                  @change="(value) => handleMinStockChange(scope.row, value - scope.row.minStock)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="零售单价" width="200">
          <template #default="scope">
            <div class="number-input">
              <el-input-number
                  v-model="scope.row.retailPrice"
                  :min="0"
                  :precision="2"
                  :step="1"
                  size="small"
                  @change="(value) => handleRetailPriceChange(scope.row, value - scope.row.retailPrice)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.stock-manage {
  padding: 0px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.number-input {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stock-warning {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-input-number) {
  width: 100px;
}

:deep(.el-table__cell) {
  padding: 1px 0;
}
</style>